package cn.lg.soar.system.auth.controller;

import cn.lg.soar.common.data.dict.DictItem;
import cn.lg.soar.common.model.HttpResult;
import cn.lg.soar.common.util.AssertUtil;
import cn.lg.soar.common.util.current.UserContext;
import cn.lg.soar.core.annotations.IdempotentByParam;
import cn.lg.soar.core.annotations.constraints.Id;
import cn.lg.soar.mvc.annotations.*;
import cn.lg.soar.system.api.constant.ModuleConst;
import cn.lg.soar.system.auth.entity.AccountBind;
import cn.lg.soar.system.auth.service.impl.AccountBindServiceImpl;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.Serializable;
import java.util.List;

/**
 * @author luguoxiang
 * @date 2021/10/16
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@Validated
@Api(tags = {"账号绑定"})
@RestController
@RequestMapping(ModuleConst.MODULE_NAME + "/account-bind")
public class AccountBindController {

    @Autowired
    private AccountBindServiceImpl service;

    private final static String SUBJECT = "账号绑定";

    @Log(value = "新增" + SUBJECT, data = "#p0", dataId = "#$r.data")
    @IdempotentByParam("#p0")
    @CreateMapping
    public HttpResult<Serializable> create(@RequestBody @Validated AccountBind data) {
        AssertUtil.isTrue(this.service.save(data), "创建失败");
        return HttpResult.<Serializable>success("创建成功")
                .setData(data.getId());
    }

    @Log(value = "修改" + SUBJECT, data = "#p0", dataId = "#p0.id")
    @UpdateMapping
    public HttpResult<Void> update(@RequestBody @Validated AccountBind data) {
        AssertUtil.isTrue(this.service.updateById(data), "更新失败");
        return HttpResult.success("更新成功");
    }

    @Log(value = "删除" + SUBJECT, data = "#p0", type = Log.Type.TEXT)
    @RemoveMapping
    public HttpResult<Void> remove(@RequestBody List<Long> ids) {
        AssertUtil.isTrue(service.removeByIds(ids), "删除失败");
        return HttpResult.success("删除成功");
    }

    @DetailMapping
    public HttpResult<AccountBind> detail(@Id Long id) {
        return HttpResult.data(this.service.getById(id));
    }

    @ListMapping
    public HttpResult<List<AccountBind>> list(){
        return HttpResult.data(service.list(
                Wrappers.<AccountBind>lambdaQuery()
                        .eq(AccountBind::getUserId, UserContext.getUserId())
        ));
    }

    @ApiOperation("获取账号类型列表")
    @GetMapping("types")
    public HttpResult<List<DictItem<Integer>>> types(){
        return HttpResult.data(service.types());
    }

}
